package com.hsmpay.Test

import com.beust.klaxon.*
import com.hsmpay.common.util.jiami.Des3
import com.hsmpay.common.util.jiami.JiamiTest
import com.hsmpay.common.util.jiami.RSAObjectC
import it.sauronsoftware.base64.Base64
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*


fun main(args: Array<String>) {
    val target = json {
        obj(
                "clientType" to 3,
                "terminalTypeId" to 1,
                "roleId" to 2
        )
    }
    target["action"] = "checkFunction_getVisibleFunction"
    println(target.toJsonString(true))
    Trans.diaoyong(target.toJsonString())
}

class Trans {
    companion object {
        var sessionId = "JSESSIONID=983A81651D1CCFE7122462A1B2FE87F1"


        @Throws(Exception::class)
        internal fun diaoyong(json: String): String {
            val terminalTypeId = String(Base64.encode("1".toByteArray(charset("UTF-8"))))
            val rsaEncrypt = RSAObjectC.getInstance(JiamiTest.publicKey, JiamiTest.privateKey)
            val desKeyB = rsaEncrypt.encrypt(rsaEncrypt.publicKey, "8C23022DD39F2AC3B4A2377813CF9AAE".toByteArray(charset("Utf-8")))
            val desKey = String(Base64.encode(desKeyB))
            println("#$desKey#")
            println("#################json#$json#")
            /*byte[] dataB = DesUtil.encrypt(json.getBytes("Utf-8"), "8C23022DD39F2AC3B4A2377813CF9AAE".getBytes("Utf-8"));
		String data = new String(Base64.encode(dataB),"UTF-8");*/
            val data = Des3.encode(json, "8C23022DD39F2AC3B4A2377813CF9AAE")

            println("#$data#")
            val str = "$terminalTypeId|$desKey|$data"//"1|"+desKey+"|"+data;
            println("参数：" + str)
            //str = Base64.encode(str);

            return httpClientUtils(str)
        }

        @Throws(Exception::class)
        internal fun httpClientUtils(XML: String): String {
            val Method = "POST"
            val xmlString = XML
            var xmlData = xmlString.toByteArray()
            try {
                xmlData = xmlString.toByteArray(charset("UTF-8"))
            } catch (e1: Exception) {
                e1.printStackTrace()
            }

            val urlStr = "http://mobile.hsmpay.com:8001/proOneMobile/forward/fc.action"
            //String urlStr = "http://42.62.5.102:8080/proOneMobile/forward/fc.action";
            //		String urlStr = "http://42.62.5.100:8000/proOneMobile/forward/fc.action";
            //String urlStr = "http://211.157.145.16:8080/zfPayMobile/forward/fc.action";//生产环境  上生产密钥得换
            var rd: BufferedReader? = null
            var msg = ""
            println("请求URL:" + urlStr)
            println("请求参数:" + XML)
            try {
                val url = URL(urlStr)
                val urlCon = url.openConnection() as HttpURLConnection
                urlCon.doOutput = true
                urlCon.doInput = true
                urlCon.useCaches = false
                urlCon.requestMethod = Method
                urlCon.connectTimeout = 120000
                urlCon.readTimeout = 120000
                //System.setProperty("sun.net.client.defaultConnectTimeout", "120000");
                //System.setProperty("sun.net.client.defaultReadTimeout", "120000");
                urlCon.setRequestProperty("Content-Type", "text/xml;charset=utf-8")
                urlCon.setRequestProperty("Content-length", xmlData.size.toString())
                urlCon.requestMethod = "POST"
                //			if(null != sessionId)
                urlCon.setRequestProperty("Cookie", "SESSION_COOKIE=s103;JSESSIONID=983A81651D1CCFE7122462A1B2FE87F1")
                //urlCon.setRequestProperty("Cookie", "JSESSIONID=BBEBB4F78F7490EC657B6EA74989DE9C");
                val printout = DataOutputStream(urlCon.outputStream)
                printout.write(xmlData)
                printout.flush()
                printout.close()
                println("数据发送完成,等待响应...")
                rd = BufferedReader(InputStreamReader(urlCon.inputStream, "utf-8"))
                var inputLine: String

                for(line in rd.readLines())
                    msg += line
                // while ((inputLine = rd.readLine()) != null)
                    // msg += inputLine
                println("解密前数据:" + msg)
                //解密
                val strArray = msg.split("\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                if (strArray.size == 3) {
                    if ("1" == strArray[0]) {
                        //成功信息
                        /*byte[] dataB = Base64.decode(strArray[1].getBytes("UTF-8"));
					String data = new String(DesUtil.decrypt(dataB, "8C23022DD39F2AC3B4A2377813CF9AAE".getBytes("UTF-8")),"UTF-8");*/
                        val data = Des3.decode(strArray[1], "8C23022DD39F2AC3B4A2377813CF9AAE")
                        strArray[1] = data
                        println("响应数据为:" + data)
                    } else {
                        val code = strArray[1]
                        println("错误代码:" + code)
                        val eMsg = String(Base64.decode(strArray[2].toByteArray(charset("UTF-8"))))
                        println("错误描述:" + eMsg)
                    }
                }

                val cookieValue = urlCon.getHeaderField("Set-Cookie")
                if (cookieValue != null) {
                    println("cookie value:" + cookieValue!!)
                    sessionId = cookieValue.substring(0, cookieValue.indexOf(";"))
                    println("sessionId:" + sessionId)
                }
                //println("响应数据为:"+msg);
                rd.close()
            } catch (e: Exception) {
                //e.printStackTrace();
                throw e
            }

            return msg
        }
    }
}